package cn.edu.sasu;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.edu.sasu.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.MessageQueue;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import cn.edu.sasu.adapter.newsdetail.newsitem.NewsItemAdapter;
import cn.edu.sasu.domain.News;
import cn.edu.sasu.http.HttpUrl;
import cn.edu.sasu.utils.ActivityUtil;
import cn.edu.sasu.view.NewsListView;
import cn.edu.sasu.view.NewsListView.OnRefreshListener;
import cn.edu.sasu.webservice.CommentService;
import cn.edu.sasu.webservice.impl.CommentServiceImpl;

/**
 * 跟帖（评论）的Activity
 * 
 * @author yubaolinfish
 * 
 */
@SuppressLint("HandlerLeak")
public class CommentActivity extends Activity {

	private NewsListView listView = null;

	private NewsItemAdapter adapter = null;
	private List<News> list = null;

	private ViewSwitcher viewSwitcher = null;

	private Button loadMoreButton = null;

	private CommentService commentService = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.comment);
		setTheme(android.R.style.Theme_Translucent_NoTitleBar);

		commentService = new CommentServiceImpl();
		viewSwitcher = (ViewSwitcher) findViewById(R.id.viewswitcher_tab_follow);

		listView = new NewsListView(this);
		listView.setCacheColorHint(Color.argb(0, 0, 0, 0));
		loadMoreButton = new Button(this);
		loadMoreButton.setBackgroundResource(R.drawable.refresh1);
		loadMoreButton.setHint(21 + "");

		loadMoreButton.setOnClickListener(buttonListener);

		listView.addFooterView(loadMoreButton);
		listView.setonRefreshListener(refreshListener);
		// 新闻列表
		viewSwitcher.addView(listView);
		// 新闻加载时候的标识，滚动效果
		viewSwitcher.addView(getLayoutInflater().inflate(
				R.layout.progress_page, null));

		viewSwitcher.showNext();// 首先显示滚动效果，表示新闻正在加载
		listView.setOnItemClickListener(listener);

		requestRSSFeed();

	}

	private int startIndex = 0;
	private int endIndex = 0;
	private final View.OnClickListener buttonListener = new View.OnClickListener() {

		@SuppressWarnings("static-access")
		@Override
		public void onClick(View v) {

			// 设置正在刷新的图片
			loadMoreButton.setBackgroundResource(R.drawable.refresh2);

			final AnimationDrawable rocketAnimation = (AnimationDrawable) loadMoreButton
					.getBackground();

			// 在Android4.0以前，这个方法是要放在操作主线程的UI中去做的，因为开始的时候，可能背景还没有绑定完成
			getMainLooper().myQueue().addIdleHandler(
					new MessageQueue.IdleHandler() {
						@Override
						public boolean queueIdle() {
							rocketAnimation.start();
							return false;
						}
					});

			startIndex = Integer.parseInt(loadMoreButton.getHint().toString());
			endIndex = startIndex + ActivityUtil.COUNT;

			new Thread() {
				@Override
				public void run() {
					list = commentService.getNews(list, startIndex, endIndex,
							HttpUrl.URL_FOLLOW);
					handler.sendEmptyMessage(3);
				}
			}.start();

		}
	};

	// 刷新
	private OnRefreshListener refreshListener = new NewsListView.OnRefreshListener() {

		@SuppressWarnings("unchecked")
		@Override
		public void onRefresh() {
			new AsyncTask<Map<String, String>, Integer, List<News>>() {

				@Override
				protected List<News> doInBackground(
						Map<String, String>... params) {
					try {
						Thread.sleep(1000);
					} catch (Exception e) {
						e.printStackTrace();
					}
					data();
					return list;
				}

				@Override
				protected void onPostExecute(List<News> result) {
					loadMoreButton.setHint(21 + "");
					listView.setAdapter(new NewsItemAdapter(list,
							CommentActivity.this));
					listView.onRefreshComplete();
				}

			}.execute();
		}
	};

	private void requestRSSFeed() {
		Thread t = new Thread() {
			@Override
			public void run() {
				super.run();
				try {
					data();// 从服务器端获取数据
					if (list.size() == 0) {
						handler.sendEmptyMessage(-1);
					} else {
						handler.sendEmptyMessage(1);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		t.start();
	}

	private void data() {
		Map<String, String> params = new HashMap<String, String>();
		params.clear();
		params.put("news.startIndex", 1 + "");
		params.put("news.endIndex", 21 + "");
		list = commentService.postAndParse(params);

	}

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 1) {
				adapter = new NewsItemAdapter(list, CommentActivity.this);
				listView.setOnItemClickListener(listener);
				listView.setAdapter(adapter);
				viewSwitcher.showPrevious();
			} else if (msg.what == 3) {

				if (list == null) {
					Toast.makeText(CommentActivity.this, R.string.no_more_news,
							Toast.LENGTH_SHORT).show();
				} else {
					adapter.notifyDataSetChanged();
					loadMoreButton.setHint(endIndex + "");
					loadMoreButton.setText(getString(R.string.gong)
							+ list.size() + getString(R.string.tiao));
				}
				loadMoreButton.setBackgroundResource(R.drawable.refresh1);

			}
		};
	};

	private OnItemClickListener listener = new AdapterView.OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			Intent intent = new Intent(CommentActivity.this,
					NewsContentActivity.class);

			intent.putExtra("content_url", list.get(position - 1).getNewsId()
					+ "");

			intent.putExtra("count", list.get(position - 1).getCommentsCount()
					+ "");

			CommentActivity.this.startActivityForResult(intent, position);
		}
	};

	private long inbacktime = 0;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if ((System.currentTimeMillis() - inbacktime) > 2000) {// 如果两次按键时间间隔大于2000毫秒，则不退出
				Toast.makeText(CommentActivity.this, R.string.doubleexit,
						Toast.LENGTH_SHORT).show();
				
				inbacktime = System.currentTimeMillis();// 更新inbacktime
			} else {
				System.exit(0);// 否则退出程序
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
